import React, { createContext, useMemo } from "react";
import { LibAppView } from "@/lib";
import lodash from "lodash";

interface IAdminPageRight {
    editable?: boolean;
    deleteable?: boolean;
    downloadable?: boolean;
    approver?: boolean;
}

interface IAdminPageProps {
    children?: any
}

interface IAdminRightProps extends IAdminPageProps {
    authRight: keyof IAdminPageRight;
    mode?: 'mount'|'disabled';
    nextProps?: any;
}

interface IAdminRoles {
    publisher: boolean;
    approver: boolean;
}

const AdminMenuContext = createContext({
    openMenu: null,
    roles: {} as IAdminRoles,
    currentRight: {} as IAdminPageRight,
    setOpenMenu: (menuData: any) => {}
});


export const AdminMenuProvider = LibAppView.withService<IAdminPageProps>({
    reqMode: "QueueList",
    reqEndPoints: [
        {
            name: "publisher",
            endPoint: "user.authPublisher",
            "withoutErrorHandle": true
        }, {
            name: "approver",
            endPoint: "user.authApprover",
            "withoutErrorHandle": true
        }, {
            name: "editor",
            endPoint: "user.authEditable",
            "withoutErrorHandle": true
        }
    ],
    "reqThrowException": false
})(({ withServiceApi, ...others }) => {
    const [openMenu, setOpenMenu] = React.useState(null);
    const [currentRight, setCurrentRight] = React.useState({} as IAdminPageRight);
    const userRoles = useMemo(() => {
        return {
            publisher: lodash.get(others.responseData,"publisher.data"),
            approver: lodash.get(others.responseData,"approver.data"),
            editable: lodash.get(others.responseData,"editor.data")
        } as any;
    }, [others.responseData]);
    const context = useMemo(() =>({
        openMenu,
        currentRight,
        roles: userRoles,
        setOpenMenu: (menuValue: any) => {
            withServiceApi.send({
                endPoint: "user.pageRight",
                uri: {
                    menuId: menuValue
                }
            }).then((resp: any) => {
                console.log(resp);
                setCurrentRight(resp.data || {});
            }).catch((err) => {
                console.error(err);
            });
        }
    }), [openMenu, currentRight, setOpenMenu, userRoles]);

    return (<AdminMenuContext.Provider value={context}>
        {(others as any).children}
    </AdminMenuContext.Provider>);
});

export const useAdminMenu = () => {
    return React.useContext(AdminMenuContext);
};

export const AdminRight = (props: IAdminRightProps) => {
    const adminMenuApi = useAdminMenu();
    let hasRight = /^1$/.test(adminMenuApi.currentRight?.[props.authRight]?.toString() ?? "");
    const mode = props.mode ?? "mount";

    const disableProps = useMemo<any>(() => {
        return hasRight ? {} : { disabled: true };
    }, [hasRight]);
    const nextProps = useMemo(() => {
        return {
            ...disableProps,
            ...(props.nextProps || {})
        };
    }, [disableProps, props.nextProps]);

    if(props.authRight === "approver" && adminMenuApi.roles.approver) {
        hasRight = true;
    }
    if(mode === "mount") {
        return hasRight ? props.children : <></>;
    } else {
        return props.children ? React.cloneElement(props.children, nextProps) : <></>
    }
};

export const useAdminRight = (authRight: keyof IAdminPageRight | keyof IAdminRoles) => {
    const adminMenuApi = useAdminMenu();
    const pageRightKey = authRight as keyof IAdminPageRight;
    const hasRight = /^1$/.test(adminMenuApi.currentRight?.[pageRightKey]?.toString() ?? "");
    const roleKeys = ["approver","publisher"];
    if(roleKeys.includes(authRight as string)) {
        return lodash.get(adminMenuApi.roles, authRight as string);
    } else {
        return hasRight;
    }
};

export const useAdminRoles = (): IAdminRoles => {
    const adminMenuApi = useAdminMenu();
    return adminMenuApi.roles;
};